﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using webapi.Entity;
using webapi.Models;
using System.Data;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace webapi.Controllers
{
    public class SettingController : ApiController
    {
      //获取设置
      [HttpGet]
      public IHttpActionResult getSetting(int curr, int limit)
      {
        List<Setting> setting = new List<Setting>();
        DataRowCollection dr = SettingService.getSetting();
        int j = curr - 1;
        int count = dr.Count;
        int len = count;
        if (count > limit)
        {
          int z = count - (j * limit);
          len = z >= limit ? limit : z;
        }
        for (int i = j; i < len + j; i++)
        {
          dr.Add(new Setting()
          {
            id = (int)dr[i][0],
            grade = dr[i][1].ToString(),
            begin = dr[i][2].ToString(),
            after = dr[i][3].ToString(),
            date = dr[i][4].ToString()
          });
        }
        return Json<dynamic>(new { code=0, count, setting });
      }

      //根据年级获取设置
      [HttpGet]
      public IHttpActionResult getSettingByGrade(string grade)
      {
        List<Setting> setting = new List<Setting>();
        DataRowCollection dr = SettingService.getSettingByGrade(grade);
        int len = dr.Count;
        for (int i = 0; i < len; i++)
        {
          dr.Add(new Setting()
          {
            id = (int)dr[i][0],
            grade = dr[i][1].ToString(),
            begin = dr[i][2].ToString(),
            after = dr[i][3].ToString(),
            date = dr[i][4].ToString()
          });
        }
        return Json<dynamic>(new { code = 0, count=len, setting });
      }

      //修改设置
      [HttpPost]
      public IHttpActionResult updateSetting([FromBody] JObject obj)
      {
        Setting setting = JsonConvert.DeserializeObject<Setting>(obj["setting"].ToString());
        int i = SettingService.updateSetting(setting);
        Boolean msg = i != -1 ? true : false;
        return Json<dynamic>(new { code = 0, msg });
      }

      //增加设置
      [HttpPost]
      public IHttpActionResult addSetting([FromBody] JObject obj)
      {
        Setting setting = JsonConvert.DeserializeObject<Setting>(obj["setting"].ToString());
        int i = SettingService.addSetting(setting);
        Boolean msg = i != -1 ? true : false;
        return Json<dynamic>(new { code = 0, msg });
      }

      //删除设置
      [HttpGet]
      public IHttpActionResult deleteSetting(int id)
      {
        int i = SettingService.deleteSetting(id);
        Boolean msg = i != -1 ? true : false;
        return Json<dynamic>(new { code = 0, msg });
      }
    }
}
